#include "debug.h"
#include "bmc_camera_app.h"
#include "bmc_version.h"
#include "bmc_mcu_i2c.h"
#include "git_bmc_camera_app_version.h"
#include "git_root_version.h"
#include "ProjectInfo.h"
#include "bmc_camera_app.h"

#define GIT_VER_FLAG "git-"
#define DATE_FMT  "YYYY/MM/DD"
#define TIME_FMT  "HH:MM"
#define GIT_DATE_TIME_FMT  GIT_VER_FLAG DATE_FMT"-"TIME_FMT"-"
#define DIRTY_FLAG "-d"
#define GIT_HASH_LEN  8
#define GIT_HASH_DIRTY_LEN  (GIT_HASH_LEN + strlen(DIRTY_FLAG))

static bmc_version_info_t bmc_version;

static void bmc_version_camera_model(bmc_version_info_t *ver)
{
    memcpy(ver->version_camera_model,Prj_GetVersionString(),strlen((const char*)Prj_GetVersionString())+1);
    snprintf(ver->version_camera_model, MAX_CHARACTER, "%s", VERSION_CAMERA_MODEL);
}

static void bmc_version_mcu(bmc_version_info_t *ver)
{
    snprintf(ver->version_mcu, MAX_CHARACTER, "V%02d", bmc_mcu_get_version());
}

static void bmc_version_soft_version(bmc_version_info_t *ver)
{
    snprintf(ver->version_soft_version, MAX_CHARACTER, "%s", VERSION_SOFT);
}

static void bmc_version_date_time(bmc_version_info_t *ver)
{
    char *ptr = (char*)(GIT_ROOT_VERSION);
    int offset = strlen(GIT_VER_FLAG);
    strncpy(ver->version_date_time, ptr + offset, strlen(DATE_FMT)); 
    strncat(ver->version_date_time, " ", strlen(" "));
    offset = strlen(GIT_VER_FLAG) + strlen(DATE_FMT) + strlen(" ");
    strncat(ver->version_date_time, ptr + offset, strlen(TIME_FMT));  
}

static void bmc_version_git_tag(char *ver_buf, char *git_ver)
{
    char *ptr = git_ver;
    int git_hash_len = GIT_HASH_LEN;

    if(!ver_buf || !ptr)
        return;
    if(strlen(git_ver) > strlen(GIT_DATE_TIME_FMT))
    {
        if(strstr(ptr, DIRTY_FLAG))
        {
            git_hash_len = GIT_HASH_DIRTY_LEN;
        }
        memcpy(ver_buf, ptr + strlen(GIT_DATE_TIME_FMT), git_hash_len); 
    }   
}

static void bmc_version_main_tag(bmc_version_info_t *ver)
{
    snprintf(ver->version_main_tag, MAX_CHARACTER,"%s",(char*)GIT_ROOT_VERSION);

}

static void bmc_version_sub_module_tag(bmc_version_info_t *ver)
{
    snprintf(ver->version_sub_module_tag, MAX_CHARACTER,"%s",(char*)GIT_bmc_camera_app_VERSION);

}

bmc_version_info_t* bmc_version_get()
{
    memset(&bmc_version,0,sizeof(bmc_version));
    bmc_version_camera_model(&bmc_version);
    bmc_version_mcu(&bmc_version);
    bmc_version_soft_version(&bmc_version);
    bmc_version_date_time(&bmc_version);
    bmc_version_main_tag(&bmc_version);
    bmc_version_sub_module_tag(&bmc_version);    
    return &bmc_version;

}

void bmc_version_print()
{
    debug_msg("root: %s\r\n", GIT_ROOT_VERSION);
    debug_msg("bca : %s\r\n", GIT_bmc_camera_app_VERSION);
}

